package net.fpeg.kotlin.msa.auth.service

import de.rtner.security.auth.spi.SimplePBKDF2
import net.fpeg.kotlin.msa.auth.dao.UserDao
import net.fpeg.kotlin.msa.auth.dto.LoginDto
import net.fpeg.kotlin.msa.auth.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class AuthService {
    @Autowired
    lateinit var jwtService: JwtService

    @Autowired
    lateinit var userDao: UserDao

    @Autowired
    lateinit var feignWordUserService: FeignWordUserService

    fun register(loginDto: LoginDto) = when (userDao.countByUsername(loginDto.username)) {
        0L -> User(
                null,
                loginDto.username,
                SimplePBKDF2().deriveKeyFormatted(loginDto.password)
        ).let {
            val user = userDao.save(it)
            user.id?.let { it1 -> feignWordUserService.register(it1) }
            return@let user
        }
        else -> throw Exception("有人")
    }


    fun login(loginDto: LoginDto) =
            userDao.countByUsername(loginDto.username)
                    .let {
                        when (it) {
                            0L -> throw Exception("无人")
                            else -> userDao.getByUsername(loginDto.username)
                        }
                    }
                    .let { user ->
                        (user.id ?: throw Exception("id为空"))
                                .let { id ->
                                    SimplePBKDF2().verifyKeyFormatted(
                                            user.password,
                                            loginDto.password
                                    ).let {
                                        when (it) {
                                            true -> jwtService.encode(id)
                                            else -> throw Exception("密码错")
                                        }
                                    }
                                }
                    }
}